package com.roadjava.rbac.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.roadjava.rbac.bean.entity.LikedDO;
import com.roadjava.rbac.bean.entity.LikedEQ;
import com.roadjava.rbac.config.RedisCache;
import com.roadjava.rbac.mapper.LikedMapper;
import com.roadjava.rbac.service.LikedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service
public class LikedServiceImpl extends ServiceImpl<LikedMapper, LikedDO> implements LikedService {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private LikedMapper likedMapper;

    @Override
    public void addLike(LikedEQ liked) {
        // 将点赞信息存入Redis
        String key = "liked:" + liked.getResourceId() + ":" + liked.getId();
        String unlikedKey = "unliked:" + liked.getResourceId() + ":" + liked.getId();
        if (redisCache.hasKey(unlikedKey)) {
            redisCache.deleteObject(unlikedKey);
            redisCache.setCacheObject(key, liked);
        }else {
            redisCache.setCacheObject(key, liked);
        }
    }

    @Override
    public void removeLike(long resourceId, long Id) {
        // 检查Redis中是否存在相同的点赞记录
        String key = "liked:" + resourceId + ":" + Id;
        String unlikedKey = "unliked:" + resourceId + ":" + Id;
        if (redisCache.hasKey(key)) {
            // 如果存在，则直接从Redis中删除该记录
            redisCache.deleteObject(key);

        } else {
            // 如果不存在，则将取消操作标记存入Redis

            redisCache.setCacheObject(unlikedKey, true);
        }
    }

    @Override
    public List<LikedDO> getUserLikes(Long userId) {
        return likedMapper.getUserLikes(userId); // 使用父类的getBaseMapper()方法
    }

    @Override
    public Long getLikeCount(Long resourceId) {
        return getBaseMapper().getLikeCount(resourceId); // 使用父类的getBaseMapper()方法
    }

    @Override
    public void saveLikedToDB() {
        // 定时任务会调用这个方法
        syncLikesToDatabase();
    }

    @Override
    public boolean checkUserLiked(Long userId, Long resourceId) {
        return getBaseMapper().existsByUserIdAndResourceId(userId, resourceId); // 使用父类的getBaseMapper()方法
    }

    /**
     * 定时任务，每隔一段时间将Redis中的点赞数据写入数据库
     */
    @Scheduled(fixedRate = 60000) // 每分钟执行一次
    public void syncLikesToDatabase() {
        Set<String> likedKeys = (Set<String>) redisCache.keys("liked:*");
        Set<String> unlikedKeys = (Set<String>) redisCache.keys("unliked:*");

        for (String key : likedKeys) {
            LikedEQ likedEQ = (LikedEQ) redisCache.getCacheObject(key);
            if (likedEQ != null) {
                LikedDO likedDO = new LikedDO();
                likedDO.setResourceId(likedEQ.getResourceId());
                likedDO.setId(likedEQ.getId());
                likedDO.setLikeStatus(likedEQ.getLikeStatus());
                // 插入或更新数据库

                likedMapper.insert(likedEQ); // 使用插入或更新操作

                // 删除Redis中的记录
                redisCache.deleteObject(key);
            }
        }

        for (String key : unlikedKeys) {
            String[] parts = key.split(":");
            Long resourceId = Long.parseLong(parts[1]);
            Long userId = Long.parseLong(parts[2]);

            // 删除数据库中的记录
            getBaseMapper().removeLike(resourceId, userId); // 使用父类的getBaseMapper()方法

            // 删除Redis中的记录
            redisCache.deleteObject(key);
        }
    }
}
